import * as actionType from "./actionType";
import { checkAuthApi } from '../../services'

export const loginTrue=()=>{
    return{
        type:actionType.LOGIN_STATUS_TRUE
    }
};
export const loginFalse=()=>{
    return{
        type:actionType.LOGIN_STATUS_FALSE
    }
};
export const checkAuth=()=>{
    //从本地存储中去取出token
    const token=window.localStorage.getItem('cors-token');
    //这里为异步action，需手动dispatch
    return (dispatch)=>{
        //没有token，直接把登录状态改为false
        if(!token){
            dispatch(loginFalse());
            dispatch({
                type:actionType.CHECK_AUTH_COMPLETED
            })
        }else{
            //有token时请求后台进行验证
            checkAuthApi(token)
                .then(resp=>{
                    if(resp.data.code===1&&resp.data.data.status==='OK'){
                        //改变登录状态为成功，
                        dispatch(loginTrue());
                    }else{
                        //改变登录状态为false
                        dispatch(loginFalse());
                    }
                })
                .catch(()=>{
                    //改变登录状态为false
                    dispatch(loginFalse());
                })
                .finally(()=>{
                    dispatch({
                        type:actionType.CHECK_AUTH_COMPLETED
                    })
                })
        }
    };
};